import React, { Component, LegacyRef } from 'react';

class GetRef extends React.Component {
  render() {
    return (
      <div className="ref">
        <StringRef />
        <hr />
        <FuncRefs />
        <hr />
        <CreateRefComp />
      </div>
    );
  }
}

class Children extends Component {
  render = () => <div>hello world</div>;
}

class StringRef extends React.Component {
  componentDidMount(): void {
    console.log('string refs');
    // “refs”已弃用
    console.log('this.refs', this.refs);
  }
  render() {
    return (
      <div className="string-ref">
        <div ref="currentDom">字符串获取元素或者组件</div>
        <Children ref="currentComInstance" />
      </div>
    );
  }
}

class FuncRefs extends React.Component {
  currentDom: HTMLDivElement | null = null;
  currentComponentInstance: Children | null = null;

  componentDidMount(): void {
    console.log('FuncRefs');
    console.log(this.currentDom);
    console.log(this.currentComponentInstance);
  }
  render() {
    return (
      <div className="func-ref">
        <div ref={(node) => (this.currentDom = node)}>函数的方式获取元素或组件</div>
        <Children ref={(node) => (this.currentComponentInstance = node)} />
      </div>
    );
  }
}

class CreateRefComp extends React.Component {
  currentDom: LegacyRef<HTMLDivElement> | undefined = React.createRef<HTMLDivElement>();
  currentComponentInstance = React.createRef<Children>();
  componentDidMount() {
    console.log('createRef');
    console.log(this.currentDom);
    console.log(this.currentComponentInstance);
  }
  render() {
    return (
      <div className="ref">
        <div ref={this.currentDom}>Ref对象模式获取元素或组件</div>
        <Children ref={this.currentComponentInstance} />
      </div>
    );
  }
}

export default GetRef;
